package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * @author lamy
 * @version 1.0
 * @ClassName: VoiceApiImpl
 * @date 2021-12-26 10:47:12
 */
@DubboService
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void add(Voice voice) {
        long nowTimes = System.currentTimeMillis();
        voice.setCreated(nowTimes);
        mongoTemplate.insert(voice);
    }

    @Override
    public Voice getVoice(List<ObjectId> objectIds, Set<Long> exclusionIds) {


        //随机取出1条推荐用户
        Criteria criteria = Criteria.where("id").nin(objectIds).and("userId").nin(exclusionIds);
        TypedAggregation<Voice> voiceTypedAggregation = TypedAggregation.newAggregation(Voice.class, Aggregation.match(criteria), Aggregation.sample(1));
        AggregationResults<Voice> aggregate = mongoTemplate.aggregate(voiceTypedAggregation, Voice.class);
        return aggregate.getUniqueMappedResult();
    }

}
